var map;
var markers = [];
var latLngs = [];
var windows = [];
var myLatlng;
var ofertaObj;
var relevanciaHTML = '';
var infowindowHTML = '';
var flag = 0;
var milkbox = null;
var marcadorAberto = null;
var markerCluster = null;
var filtro = [];

var getRelevancia = new Request({
    url : 'include/request/getRelevancia.php',
    onSuccess: function(response){
	relevanciaHTML = response;
    },
    async:false
});

var getInfowindow = new Request({
    url : 'include/request/getInfowindow.php',
    onSuccess: function(response){
	infowindowHTML = response;
    },
    async:false
});

var addLido = new Request({
    url : 'include/request/addLido.php',
    async:false
});


function initialize() {
    
    var lat, lng, zoom;
    
    lat = -22.950944078667128;
    lng = -43.18862902539058;
    zoom = 13;
    
    var myLatlng = new google.maps.LatLng(lat, lng);
    var myOptions = {
	zoom: zoom,
	center: myLatlng,
	mapTypeId: google.maps.MapTypeId.ROADMAP,
	mapTypeControl: false
    }
    
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function placeMarkerRead(location, index) {

    var marker = new google.maps.Marker({
		position	: location.latLng,
		map		: map,
		icon		: location.icone,
		id		: location.id,
		id_usuario	: location.id_usuario,
		lido		: location.lido,
		location	: location,
		infowindow	: null,
		clusters	: false,
		isAdded		: false,
		blCompartilhado : location.blCompartilhado,
		blQuote		: location.blQuote
    });	   


    google.maps.event.addListener(marker, 'click', function() {
	
	console.log(marker);
	
	if(marcadorAberto != null){
	    markers[marcadorAberto].infowindow.setMap(null);
	}
	
	marcadorAberto = index;
	
	addLido.post({id_marcador:marker.id});
	marker.lido = 1;

	getRelevancia.post({id_mapa:marker.id});
	location.relev = relevanciaHTML;

	getInfowindow.post({
	    relev	: relevanciaHTML,
	    latLng	: location.latLng,
	    conteudo	: location.conteudo,
	    icone	: location.icone,
	    dtPost	: location.dtPost,
	    titulo	: location.titulo,
	    id		: location.id,
	    id_usuario	: location.id_usuario,
	    nome	: location.nome,
	    dataFim	: location.dataFim,
	    mostrarSeguir   : location.mostrarSeguir,
	    minhaPosicao    : index,
	    qtdMarkers	    : markers.length,
	    fotos	    : location.fotos,
	    compartilhado	    : location.compartilhado,
	    id_compartilhado	    : location.id_compartilhado
	});
	
	var infoBox = new InfoBox({
				    latlng: marker.getPosition(), 
				    map: map, 
				    conteudo:infowindowHTML,
				    enableEventPropagation: true
				});
				
				
	
	// infoBox.setZIndex(9999);

//	var infowindow = new google.maps.InfoWindow({
//	    content: infowindowHTML
//	});

	relevanciaHTML = '';
//	infowindow.open(map, marker);
	
	marker.infowindow = infoBox;
	
	map.setCenter(marker.position);
	
//	for (i = 0; i < markers.length; i++) {
//	    markers[i].setClickable(false);
//	    
//	}
	
	
    });

    markers.push(marker);
}



function cluster_reload(){
   markerCluster.redraw();
}

Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
}

function mostrarMarcador(anterior, i){
    
    if(anterior < i)
		subindo = true;
    else
		subindo = false;
    
    anterior = anterior.mod(markers.length);    
    i = i.mod(markers.length);
    
    console.log(markers[i].location.titulo + ": " + anterior + " -> " + i);
    
    if(markers[anterior].infowindow != null)
		markers[anterior].infowindow.setMap(null); 
	
	//markers[anterior].infowindow.close();  
    
    if(markers[i].map == null){	
		
		if(subindo)
			proximo = (i+1).mod(markers.length);
		else
			proximo = (i-1).mod(markers.length);
		
		mostrarMarcador(i, proximo);
		
		return false;
    }
    
    var marker =  markers[i];
    var location = marker.location;
       
    
    addLido.post({id_marcador:marker.id});
    marker.lido = 1;

    getRelevancia.post({id_mapa:marker.id});
    location.relev = relevanciaHTML;
    
    getInfowindow.post({
	relev	: relevanciaHTML,
	latLng	: location.latLng,
	conteudo	: location.conteudo,
	icone	: location.icone,
	dtPost	: location.dtPost,
	titulo	: location.titulo,
	id		: location.id,
	id_usuario	: location.id_usuario,
	nome	: location.nome,
	dataFim	: location.dataFim,
	mostrarSeguir : location.mostrarSeguir,
	minhaPosicao : i,
	qtdMarkers : markers.length,
	fotos	: location.fotos,
	compartilhado	    : location.compartilhado,
	id_compartilhado    : location.id_compartilhado
    });
    
//    var infowindow = new google.maps.InfoWindow({
//	content: infowindowHTML
//    });

    if(marcadorAberto != null){
	markers[marcadorAberto].infowindow.setMap(null);
    }

    marcadorAberto = i;

    var infoBox = new InfoBox({latlng: marker.getPosition(), map: map, conteudo:infowindowHTML});

    markers[i].infowindow = infoBox;
	
    map.setCenter(markers[i].position);

//    infowindow.open(map, marker);
}

function teste(){
	return markers;
}

function deleteOverlays() {
      if (markers) {
	  for (i = 0; i < markers.length; i++) {
	      markers[i].setMap(null);
		markers[i] = null;
	      
	  }
    
	    markers.length = 0;
	}     
}

function printingMarkers(arrMarkers) {
    for (i = 0; i < arrMarkers.length; i++) {
	   placeMarkerRead(arrMarkers[i], i);
    }
}

var marker = new google.maps.Marker({
    position:myLatlng,
    map: map
});

google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
});

var read = new Request.JSON({
	url: 'include/request/read.php',
	async: false,
	onSuccess: function(responseJSON ){

		var coordenadas = responseJSON;

		var lat,lng,latLng,conteudo,icone, dtPost,titulo,id,id_usuario,nome,dataFim,lido,fotos;
		var compartilhado , id_compartilhado, blCompartilhado, blQuote;

		var ofertas = [];

		for (i = 0; i < coordenadas.length; i++) {

			lat	    = coordenadas[i].lat;
			lng	    = coordenadas[i].lng;
			conteudo    = coordenadas[i].content;
			icone	    = coordenadas[i].icon;
			dtPost	    = coordenadas[i].dtPost;
			titulo	    = coordenadas[i].titulo;
			id	    = coordenadas[i].id;
			id_usuario  = coordenadas[i].id_usuario;
			nome	    = coordenadas[i].nome;
			lido	    = coordenadas[i].lido;
			fotos	    = coordenadas[i].fotos;

			latLng	    = new google.maps.LatLng(lat,lng);
			dataFim	    = coordenadas[i].dataFim;
			
			compartilhado		= coordenadas[i].compartilhado;
			id_compartilhado	= coordenadas[i].id_compartilhado;
			
			if(compartilhado != "" && compartilhado != "quote")
			    blCompartilhado = true;
			else{
			    blCompartilhado = false;
			}
			
			if(compartilhado == "quote")
			    blQuote = true;
			else
			    blQuote = false;
			    

			ofertaObj   = {
			    latLng	: latLng,
			    conteudo	: conteudo,
			    icone	: icone,
			    dtPost	: dtPost,
			    titulo	: titulo,
			    id		: id,
			    id_usuario	: id_usuario,
			    nome	: nome,
			    dataFim	: dataFim,
			    lido	: lido,
			    fotos	: fotos,
			    compartilhado	 : compartilhado,
			    id_compartilhado : id_compartilhado,
			    blCompartilhado : blCompartilhado,
			    blQuote : blQuote
			};

			ofertas.include(ofertaObj);
		}
		printingMarkers(ofertas);


	}
});

if(typeof perfil != 'undefined'){

    var readPerfil = new Request.JSON({
	    url: 'include/request/readPerfil.php?id_perfil=' + id_perfil,
	    async: false,
	    onSuccess: function(responseJSON ){
		    
		    var coordenadas = responseJSON;

		    var lat,lng,latLng,conteudo,icone, dtPost,titulo,id,id_usuario,nome,dataFim,lido,fotos,compartilhado,id_compartilhado;

		    var ofertas = [];

		    for (i = 0; i < coordenadas.length; i++) {

			    lat		= coordenadas[i].lat;
			    lng		= coordenadas[i].lng;
			    conteudo    = coordenadas[i].content;
			    icone	= coordenadas[i].icon;
			    dtPost	= coordenadas[i].dtPost;
			    titulo	= coordenadas[i].titulo;
			    id		= coordenadas[i].id;
			    id_usuario  = coordenadas[i].id_usuario;
			    nome	= coordenadas[i].nome;
			    lido	= coordenadas[i].lido;
			    fotos	= coordenadas[i].fotos;
			    
			    compartilhado	= coordenadas[i].compartilhado;
			    id_compartilhado	= coordenadas[i].id_compartilhado;
				
			    latLng	    = new google.maps.LatLng(lat,lng);
			    dataFim	    = coordenadas[i].dataFim;
			    
			    
			    
			    ofertaObj   = {
				latLng	: latLng,
				conteudo: conteudo,
				icone	: icone,
				dtPost	: dtPost,
				titulo	: titulo,
				id	: id,
				id_usuario : id_usuario,
				nome	: nome,
				dataFim	: dataFim,
				lido	: lido,
				fotos	: fotos,
				compartilhado	 : compartilhado,
				id_compartilhado : id_compartilhado
			    };
			    
			    ofertas.include(ofertaObj);
		    }
		    printingMarkers(ofertas);


	    }
    });

}


function read1(){
    
    deleteOverlays();    
    
    if(typeof perfil != 'undefined'){
	readPerfil.send();
	cluster_init(); 
    }else{  
	read.send();
	cluster_init(); 
	marcadoresIniciais();
    }
    
       
}

function marcadoresIniciais(){
    for(j=0;j<markers.length;j++){
	if(markers[j].lido != 0){
	    markers[j].setMap(null);
	    if(markerCluster != null )
		markerCluster.removeMarker(markers[j]);
	}		
    }
}



window.addEvent('domready', function(){

	var save = new Request({
		url: 'include/request/save.php'
	});

	$$('.save').addEvent('click',function(){
			var m = teste();
			save.post({markers:m});
	});

	$$('.read').addEvent('click',function(){
			read.send();
	});

	$$('.deleteAll').addEvent('click',function(){
			deleteOverlays();
	});
});

var readBusca = new Request.JSON({
	url: 'include/request/readBusca.php',
	async: false,
	onSuccess: function(responseJSON){

		var coordenadas = responseJSON;

		var lat,lng,latLng,conteudo,icone, dtPost,titulo,id,id_usuario,nome,dataFim,lido,mostrarSeguir,fotos;
		latLng = null;
		var ofertas = [];

		for (i = 0; i < coordenadas.length; i++) {

			lat	    = coordenadas[i].lat;
			lng	    = coordenadas[i].lng;
			conteudo    = coordenadas[i].content;
			icone	    = coordenadas[i].icon;
			dtPost	    = coordenadas[i].dtPost;
			titulo	    = coordenadas[i].titulo;
			id	    = coordenadas[i].id;
			id_usuario  = coordenadas[i].id_usuario;
			nome	    = coordenadas[i].nome;
			lido	    = coordenadas[i].lido;
			mostrarSeguir = coordenadas[i].mostrarSeguir;
			fotos = coordenadas[i].fotos;

			latLng	    = new google.maps.LatLng(lat,lng);
			dataFim	    = coordenadas[i].dataFim;

			ofertaObj   = {
			    latLng	: latLng,
			    conteudo	: conteudo,
			    icone	: icone,
			    dtPost	: dtPost,
			    titulo	: titulo,
			    id		: id,
			    id_usuario	: id_usuario,
			    nome	: nome,
			    dataFim	: dataFim,
			    lido	: lido,
			    mostrarSeguir : mostrarSeguir,
			    fotos	: fotos
			};

			ofertas.include(ofertaObj);
		}
		printingMarkers(ofertas);
		
		if(latLng != null)
		    map.setCenter(latLng);
	}
});

function readBusca1(){
    readBusca.send();
}
